/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */

package org.sbbs.base.jpa.suppert;

import org.hibernate.envers.RevisionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * <b>描述:</b><br/>
 * <br/>
 * <p>
 * 说明描述用途及关键点,算法等
 * <p>
 * <b>创建时间:</b> 2025年3月21日 17:55:17 <br/>
 * <b>作者:</b> Mr.FDC <fdc_messenger@126.com> <br/>
 *
 * <p>
 * <b>修改记录:</b><br/>
 * <ol>
 * <li>......</li>
 * </ol>
 */
@Component
public class CustomRevisionEntityListener implements RevisionListener {
    @Autowired
    SpringSecurityAuditorAware springSecurityAuditorAware;

    public void newRevision(Object revisionEntity) {
        CustomRevisionEntity customRevisionEntity = (CustomRevisionEntity) revisionEntity;
        Optional<User> u = springSecurityAuditorAware.getCurrentAuditor();
//        if (u == null)
//            customRevisionEntity.setUsername("default");
//        else
//            customRevisionEntity.setUsername(u.getUsername() == null ? "default" : u.getUsername());

        u.ifPresentOrElse(user -> {
            customRevisionEntity.setUsername(user.getUsername() == null ? "default" : user.getUsername());
        }, () -> {
            customRevisionEntity.setUsername("default");
        });

    }

}